<template>
  <div class="article-list-page">
    <div class="gp-filter">
      <!-- <div class="mk-cus-ddl">
        <span class="cur">最受欢迎</span>
        <div class="sub-dd-block">
          <ul class="sub-ddls">
            <li><a>全部</a></li>
            <li><a>游戏</a></li>
            <li><a>作品</a></li>
            <li><a>截图</a></li>
            <li><a>短视频</a></li>
          </ul>
        </div>
      </div> -->
      <DropDown :list="tagFilter" :value.sync="queryParams.rank" :tlist="tList" :subvalue.sync="queryParams.orderByColumn" @change="handleSearch()"  style="min-width: 150px;" placeholder=""/>
      <div class="seach-bx" :class="{'active':isFocus}">
        <form @submit.prevent="() => { return false }">
          <input type="text" @focus="isFocus = true" @blur="isFocus = false"
            :placeholder="'按标题/风格/类型等搜索 '+total+' 个文章'" v-model="queryParams.title" @keypress.enter="handleSearch" /><a class="cancel-search" v-if="queryParams.title" @click="queryParams.title=''"></a>
        </form>
      </div>
      <!-- <div class="bs-layout">
        <div class="plat-items">
          <span class="f-layout" :class="{ 'active': model == 'big' }" @click="model = 'big'"></span>
          <span class="mup-layout" :class="{ 'active': model == 'small' }" @click="model = 'small'"></span>
        </div>
      </div> -->
      <div class="bs-g-flabel">
        <span class="cur">筛选</span>
        <div class="games-filter">
          <div class="games-filter-wrap">
            <div class="gft-data-box">
              <ul class="data-ul">
                <li v-for="(cate, idx) in filterRows" :key="idx">
                  <a :class="{ active: queryParams.categoryId==cate.id }" @click="queryParams.categoryId=queryParams.categoryId==cate.id?9:queryParams.categoryId=cate.id;handleSearch();">{{ cate.title }}</a>
                </li>
              </ul>
            </div>

            <div class="bot-btns">
              <a class="cancel" @click="handleCancelAllCate">全部取消</a>
              <a class="confirm" @click="handleConfirmSelectCate">确定</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ul class="games-data" :class="[model]">
      <li v-for="(item, idx) in list" :key="idx" class="dx-vd-item" :class="{'no-data':!item.id}">
        <a class="fav-d-item" :href="'/article/'+item.id" target="_blank" v-if="item.id">
          <div class="img-flex-box">
            <div class="main-img">
              <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy" @error="loadError"/>
            </div>
          </div>
          <div class="bot-desc">
            <span class="file-name">{{ item.title }}</span>
          </div>
          <div class="bot-author">
            <a class="u" @click.stop="toUsercenter(item.member.id)">
              <span class="img-box">
                <img loading="lazy" v-aimgd="{ avatar: item.member.avatar, id: item.member.id, w: 20, name: item.member.userName }" />
              </span>
              <span class="name">{{ item.member.userName }}<img loading="lazy" class="u-m-tag" v-for="tag in item.member.tagsList" :src="tag.image" alt=""></span>
            </a>
            <div class="rt">
              <span class="like-num">{{ item.praiseStr }}</span>
              <div class="vnum">
                    {{ item.seeStr }}
                  </div>
            </div>
          </div>
        </a>
      </li>
    </ul>
    <div class="no-more-text" v-if="!hasMore&&!isloading&&list.length>0">没有更多了</div>
    <Empty text="没有找到符合条件的结果~" v-if="!isloading&&list.length==0&&!isDataError"/>

    <div class="web-data-error" v-if="isDataError">
      <div class="tip-text">别走开刷新一下，有所爱才有所期待～</div>
      <div class="options">
        <a class="go-back" href="/">返回首页</a>
        <a class="click-refresh" @click="isDataError = false; handleSearch();">点击刷新</a>
      </div>
    </div>

    <div class="pro-bot-loading" v-if="isloading">
        <i class="el-icon-loading"></i>
    </div>

    <!-- <transition name="fade"> -->
    <el-drawer :with-header="false" destroy-on-close :modal="false" append-to-body  :visible.sync="showInfo" direction="btt">
      <articleInfo @close="onInfoClose" :id="currentId" />
    </el-drawer>
    <!-- </transition> -->
    <div class="loading-mask" v-if="isloading"></div>
  </div>
</template>

<script>
import Empty from '@/components/Empty'
import DropDown from '@/components/dropdown'
import pswiper from '@/components/pswiper'
import articleInfo from '@/components/articleinfo'
import api from '@/api/api'
export default {
  components: { articleInfo, pswiper,DropDown,Empty},
  data() {
    return {
      isDataError:false,
      isloading:true,
      tList:[],
      filterRows:[],
      tagFilter:[],
      infoUrlEnum: {
        22: { url: '/game/', name: '游戏' },
        1: { url: '/work/', name: '作品' },
        50: { url: '/video/', name: '短视频' },
        9: { url: '/article/', name: '文章' }
      },
      isFocus: false,
      model: 'small',
      currentId: '',
      showInfo: false,
      keyword: '',
      gTypes: [],
      list: [],
      queryParams: {
        orderByColumn: 'createTime',
        pageSize: 20,
        pageNum: 1,
        isAsc: 'desc',
        rank: '首页推荐',
        categoryId: 9
      },
      total: 0,
      hasMore: true,
      scrollLoaded: false,
      allCates: [],
      curAllCateKey: '',
      curCates: [],
      curFullPath: ''
    }
  },
  destroyed() {
    window.removeEventListener('scroll',this.onscroll)
  },
  async mounted() {
    $('body,html').animate({ scrollTop: 0 }, 300);
    // let start = new Date();
    // let starttime = moment(start).format('YYYY-MM-DD');
    // let end = new Date(start.setDate(start.getDate() + 1));
    // let endtime = moment(end).format('YYYY-MM-DD')
    // // let res = await api.articlelist({ orderByColumn: 'see', isAsc: 'desc', startTime: starttime, endTime: endtime, pageNum: 1, pageSize: 8 })
    let res=await api.getCategoryFilter({type:'discover'});
    this.tagFilter=res.data.tags.filter(r=>{
      return r.title!='编辑精选'&&r.title!='普通推荐'
    });
    this.tList=res.data.news;
    res=await api.getChildrenListByParentId({parentId:9});
    this.filterRows=res.data;

    this.curFullPath = this.$route.fullPath;

    let _gTypes = localStorage.getItem('G-TYPES')
    _gTypes = JSON.parse(decodeURIComponent(_gTypes))
    this.gTypes = _gTypes

    let _allCates = JSON.parse(decodeURIComponent(localStorage.getItem('CATE-ALL-TYPES')))
    this.curAllCateKey = _allCates[1].key
    this.allCates = _allCates

    let _k=this.$route.query.k;
    if(_k){
        this.queryParams.title=_k;
    }
    this.queryList()
    window.addEventListener('scroll',this.onscroll)
  },
  methods: {
    loadError(e){
        e.target.removeAttribute('srcset');
    },
    onscroll(e){
      let that=this;
      if (that.showInfo) return
      let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight

      if (that.scrollLoaded == false) return
      if (jHeight <= 200 && that.hasMore) {
        if (!localStorage.getItem('token')) {
            that.$parent.$parent.noLoginIsTak = false;
            that.$parent.$parent.showLoginView = true;
            that.isloading = false;
            window.removeEventListener('scroll', that.onscroll);
            return;
        }
        that.scrollLoaded = false;
        that.loadMore();
      }
    },
    handleXClear(){
      this.queryParams={
        orderByColumn: 'createTime',
        pageSize: 20,
        pageNum: 1,
        isAsc: 'desc',
        rank: '首页推荐',
        categoryId: 9
      }
      this.handleSearch();
    },
    toUsercenter(id) {
      let routeData = this.$router.resolve({ path: "/user/" + id });
      window.open(routeData.href, '_blank');
    },
    handleSearch(e) {
      if(e)e.target.blur();
      window.history.pushState({}, 0,e&&e.target.value?('?t=9&k='+e.target.value):'?t=9');
      this.queryParams.pageNum = 1;
      this.list = [];
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    onInfoClose() {
      window.history.pushState({}, 0, this.curFullPath);
      document.body.style.overflow = 'inherit';
      this.showInfo = false;
    },
    handleShowInfo(_item) {
      window.history.pushState({}, 0, '/article/' + _item.id);
      this.currentId = _item.id;
      document.body.style.overflow = 'hidden';
      this.showInfo = true;
    },
    handleCancelAllCate() {
      this.queryParams.categoryId=9;
      this.handleSearch();
    },
    handleConfirmSelectCate() {
      let datas = this.allCates.filter((r) => {
        return r.key == 'theme'
      })[0].result;

      let tags = [];
      datas.map(item => {
        if (item.checked) {
          tags.push(item.title);
        }
      })
      datas = this.allCates.filter((r) => {
        return r.key == 'style'
      })[0].result;

      let style = '';
      datas.map(item => {
        if (item.checked) {
          style = item.title;
        }
      })

      let categoryIds = [];
      datas = this.allCates.filter((r) => {
        return r.key == 'categoryThirdId'
      })[0].result;
      datas.map(item => {
        if (item.checked) {
          categoryIds.push(item.id);
        }
      })

      datas = this.allCates.filter((r) => {
        return r.key == 'era'
      })[0].result;

      let era = '';
      datas.map(item => {
        if (item.checked) {
          era = item.title;
        }
      })

      this.queryParams.tags = tags;
      this.queryParams.style = style;
      this.queryParams.categoryIds = categoryIds;
      this.queryParams.era = era;
      this.queryParams.pageNum = 1;
      this.list = [];
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    loadMore() {
      this.queryParams.pageNum++
      this.queryList()
    },
    queryList() {
      var that = this

      this.isloading=true;
      // const loading = this.$loading({
      //     lock: true,
      //     text: '努力加载中...',
      //     spinner: 'el-icon-loading',
      //     background: 'rgba(0, 0, 0, 0.7)'
      // });
      if(that.queryParams.pageNum==1){
        that.list=[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}];
      }
      api.articlelist(that.queryParams).then(result=>{
        if(that.queryParams.pageNum==1){
            that.list=[];
        }
        setTimeout(()=>{
          that.isloading = false;
        },300)

        let old = that.list;
        let domainUrl=that.$imgdomainurl;
        result.data.map(item=>{
          let _vtime=null;
          if(item.updateTime){
            _vtime=item.updateTime;
          }else if(item.createTime){
            _vtime=item.createTime;
          }else if(item.create_time){
            _vtime=item.create_time.replace('T',' ');
          }
          _vtime=Math.abs(new Date(_vtime).getTime());
          let srcsets=[];
          srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@1x432.webp 1x');
          srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@2x432.webp 2x');
          srcsets.push(domainUrl+'article-'+item.id+'-'+_vtime+'@3x432.webp 3x');
          item.srcsets=srcsets.join(',')
          item.lazy={
            src:domainUrl+'article-'+item.id+'-'+_vtime+'@1x432.webp',
            error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
            loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
          }
        })
        that.list = [...old, ...result.data];

        that.total = result.total;

        let totalPage = result.total % that.queryParams.pageSize == 0 ? result.total / that.queryParams.pageSize : parseInt(result.total / that.queryParams.pageSize) + 1
        if (result.data && (result.data.length < that.queryParams.pageSize || that.queryParams.pageNum >= totalPage)) {
          that.hasMore = false;
        } else {
          that.hasMore = true;
        }
        that.scrollLoaded = true;
      }).catch(e=>{
        that.isloading=false;
        that.isDataError=true;
      })
      
    }
  }
}
</script>

<style lang="less">
.article-list-page {
  // min-height:calc(100vh - 84px - 84px - 44px - 64px);
  .gp-filter {
    
    position:relative;
    top: 0px;
        // z-index:1;
        // margin-top:20px;
        // padding-top:10px;
        // margin-bottom:21px;
        padding-bottom:21px;
        padding-top:10px;
        margin-bottom:0px;
        margin-top:0px;
  }
}
</style>